<template>
  <div class="default-main ba-table-box">
    <!-- 表格顶部菜单 -->
    <TableHeader
      :buttons="['refresh', 'comSearch', 'columnDisplay']"
      :quick-search-placeholder="placeholder"
      @action="baTable.onTableHeaderAction"
    />
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table ref="tableRef" @action="baTable.onTableAction" />
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  provide,
  onMounted,
  markRaw,
  reactive,
  onBeforeUnmount,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { ProductionPlan } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import TagVue from "./components/tag.vue";
import TagSearch from "@/components/tagSearch/index.vue";
import { useRoute, useRouter } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useNavTabs } from "@/store/navTabs";
import { getDictData } from "@/utils/common";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useProductionPlan } from "@/store/backend/ProductionPlan/plan";
import { useBomM } from "@/store/backend/BomM/bomM";
import { useBomDict } from "@/store/backend/BomM/bomDict";
import { useFactoryStation } from "@/store/backend/FactoryM/stationInfo";
import { useProductionWorkOrder } from "@/store/backend/ProductionPlan/workOrder";
import { ElMessage, ElMessageBox } from "element-plus";
import PlanStateTag from "./components/planStateTag.vue";
import productTypeTag from "./components/productType.vue";
import isSuspendTag from "./components/isSuspendTag.vue";
import isProductTag from "./components/isProductTag.vue";

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const plan = useProductionPlan();
const bom = useBomM();
const bomD = useBomDict();
const station = useFactoryStation();
const planOrder = useProductionWorkOrder();
const isDrawerShow = ref(false);

let drawList = reactive({});

//全局事件总线
const { proxy } = useCurrentInstance();

const state: { feedback: boolean } = reactive({ feedback: false });

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + ProductionPlan)
      ? (navTabs as any).pageSizeMap.get(route.path + ProductionPlan)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(ProductionPlan), //this.api = api部门管理
  {
    expandAll: true,
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("code"),
        label: "计划号",
        prop: "code",
        align: "left",
        operatorPlaceholder: "模糊搜索",
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (row.planState !== null && row.planState - 0 == 5) {
            //异常
            return "<p style='color:red;'>" + value + "</p>";
          }
          return "<p>" + value + "</p>";
        },
      },
      {
        show: filedShowOff("name"),
        label: "批次号",
        prop: "name",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("planState"),
        label: "计划状态",
        prop: "planState",
        align: "center",
        width: "80",
        render: "customRender",
        customRender: markRaw(PlanStateTag),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("productCode"),
        label: "产品编码",
        prop: "productCode",
        align: "left",
        width: 110,
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("productName"),
        label: "产品名称",
        prop: "productName",
        align: "left",
        width: 150,
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("materialType"),
        label: "产品类型",
        prop: "materialType",
        align: "left",
        operatorPlaceholder: "模糊搜索",
      },
      {
        show: filedShowOff("planQuantity"),
        label: "计划数",
        prop: "planQuantity",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("productQuantity"),
        label: "投产数",
        prop: "productQuantity",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("productRate"),
        label: "加工进度",
        prop: "productRate",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("processRoute"),
        label: "工艺路线",
        prop: "processRoute",
        align: "left",
        operator: false,
      },
      {
        show: filedShowOff("productType"),
        label: "生产类型",
        prop: "productType",
        align: "left",
        render: "customRender",
        customRender: markRaw(productTypeTag),
        operator: false,
      },

      {
        show: filedShowOff("isSuspend"),
        label: "是否暂停",
        prop: "isSuspend",
        align: "center",
        width: "80",
        render: "customRender",
        customRender: markRaw(isSuspendTag),
        operator: false,
      },
      {
        show: filedShowOff("startTime"),
        label: "计划开始时间",
        prop: "startTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("endTime"),
        label: "计划结束时间",
        prop: "endTime",
        align: "center",
        render: "datetime",
      },
      {
        show: filedShowOff("deliverDate"),
        label: "交付日期",
        prop: "deliverDate",
        align: "center",
        // render: "datetime",
        operator: false,
      },
      {
        show: filedShowOff("priority"),
        label: "优先级",
        prop: "priority",
        align: "center",
        render: "customRender",
        customRender: markRaw(TagVue),
        comSearchRender: "customRender",
        comSearchCustomRender: markRaw(TagSearch),
      },
      {
        show: filedShowOff("workshopName"),
        label: "加工车间",
        prop: "workshopName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("origin"),
        label: "计划来源",
        prop: "origin",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("isProduct"),
        label: "是否排产",
        prop: "isProduct",
        align: "center",
        render: "customRender",
        customRender: markRaw(isProductTag),
        operator: false,
      },
      {
        show: filedShowOff("materialState"),
        label: "物料准备状态",
        prop: "materialState",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("toolState"),
        label: "工装准备状态",
        prop: "toolState",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("remark"),
        label: "提示",
        prop: "remark",
        align: "center",
        operator: false,
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          if (row.planState !== null && row.planState == 5) {
            //异常
            return "<p style='color:red;'>" + value + "</p>";
          }
          return "";
        },
      },
      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: "操作",
        align: "center",
        operator: false,
        render: "buttons",
        fixed: "right",
        width: "220",
        buttons: [
          {
            render: "tipButton",
            name: "dispatch",
            title: "派工",
            text: "",
            type: "primary",
            icon: "iconfont icon-houtaiguanli-kehu",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "suspend",
            title: "暂停",
            text: "",
            type: "danger",
            icon: "el-icon-VideoPlay",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "dropdown",
            name: "dropdown",
            title: "更多",
            text: "",
            type: "primary",
            icon: "iconfont icon-xinzeng",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {
              dropdown: [
                // {
                //   name: "edit",
                //   title: "编辑",
                //   icon: "iconfont icon-pencil",
                //   class: "table-row-dropdown",
                // },
                {
                  name: "info",
                  title: "详情",
                  icon: "iconfont icon-chaxunyujisuan",
                  class: "table-row-dropdown",
                },
                {
                  name: "wander",
                  title: "流转卡",
                  icon: "el-icon-Document",
                  class: "table-row-dropdown",
                },
                {
                  name: "feedback",
                  title: "问题反馈",
                  icon: "el-icon-ChatDotSquare",
                  class: "table-row-dropdown",
                },
              ],
            },
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {
      maxHeight: 580,
    },
  },
  {
    defaultItems: { isSuspend: "0", isProduct: "0" },
  },
  {}
);

//获取计划状态/是否暂停的字典
const getMenuStatus = () => {
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["productType"])
  ) {
    dictionary.getDictInfo("sys_plan_producttype").then((res: any) => {
      dictionary.moreTags["productType"] = getDictData(res);
      plan.options["productType"] = res;
      console.log("获取生产类型的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["planState"])
  ) {
    dictionary.getDictInfo("sys_plan_state").then((res: any) => {
      dictionary.moreTags["planState"] = getDictData(res);
      plan.options["planState"] = res;
      console.log("获取计划状态的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["isSuspend"])
  ) {
    dictionary.getDictInfo("sys_plan_suspend").then((res: any) => {
      dictionary.moreTags["isSuspend"] = getDictData(res);
      plan.options["isSuspend"] = res;
      console.log("获取是否暂停的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["priority"])
  ) {
    dictionary.getDictInfo("sys_plan_priority").then((res: any) => {
      dictionary.moreTags["priority"] = getDictData(res);
      plan.options["priority"] = res;
      console.log("获取优先级的字典", dictionary.moreTags);
    });
  }
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["isProduct"])
  ) {
    dictionary.getDictInfo("sys_plan_isproduct").then((res: any) => {
      dictionary.moreTags["isProduct"] = getDictData(res);
      plan.options["isProduct"] = res;
      console.log("获取是否排产的字典", dictionary.moreTags);
    });
  }
};
getMenuStatus();

// //跳转详情页
// const infoButtonClick = (id: number, row: any) => {
//   console.log("id", id, "row", row);
//   plan.$patch((state) => {
//     state.single = row;
//     state.planId = row.id;
//   });
//   router.push({
//     path: "/admin/ProductionPlan/detail",
//     query: { materialCode: row.productCode, materialType: row.materialType },
//   });
// };

//派工
const toggleDispatch = (id: number, row: any) => {
  console.log("派工", id, "row", row);
  planOrder.$patch((state) => {
    state.getOrder = row;
    state.isDrawerShow = true;
    proxy.eventBus.emit("workOrderDrawer");
  });
  // proxy.eventBus.emit("workOrderDrawer");
};

onMounted(() => {
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(ProductionPlan);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      console.log("表格内的按钮响应", data);
      switch (data.name) {
        case "wander":
          //流转卡
          break;
        case "feedback":
          //问题反馈
          break;
        // case "info":
        //   //详情页面
        //   infoButtonClick(
        //     (data.row as TableRow)[baTable.table.pk!],
        //     data.row as any
        //   );
        //   break;
        case "dispatch":
          //派工
          toggleDispatch(
            (data.row as TableRow)[baTable.table.pk!],
            data.row as any
          );
          break;
      }
    }
  );
});

onBeforeUnmount(() => {
  proxy.eventBus.off("workOrderDrawer");
  proxy.eventBus.off("onTableButtonClick");
});

// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("plan", plan);
provide("bom", bom);
provide("bomD", bomD);
provide("station", station);
</script>
<style lang="scss" scoped>
.default-main {
  margin: 0px !important;
  margin-bottom: 30px !important;
}
</style>
